package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.dto.UpdateSetmealDto;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.ISetmealService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.vo.SetmealVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 套餐 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-07-02
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {

    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Override
    public PageResult getPage(SetmealPageQueryDTO dto) {
        Page<Setmeal> page = this.page(new Page<>(dto.getPage(), dto.getPageSize()));

        IPage<SetmealVO> setmealCategoryPage = setmealMapper.selectSetmealWithCategory(page, dto.getStatus(), dto.getCategoryId(), dto.getName());
        return new PageResult(setmealCategoryPage.getTotal(), setmealCategoryPage.getRecords());
    }

    @Override
    public SetmealVO getSeatmealById(Long id) {
        SetmealVO setmealVO=  setmealMapper.getSeatmealById(id);
        List<SetmealDish> setmealDishes=setmealDishMapper.selectBySeatmealId(id);
        setmealVO.setSetmealDishes(setmealDishes);
       return setmealVO;
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void updateSetmeal(UpdateSetmealDto dto) {
        Setmeal setmeal = BeanUtil.copyProperties(dto, Setmeal.class);
        this.updateById(setmeal);
        List<SetmealDish> setmealDishes = dto.getSetmealDishes();
        if (!CollectionUtils.isEmpty(setmealDishes)) {
            setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(dto.getId()));
            setmealDishMapper.insertBatch(setmealDishes);
        }
    }

    @Override
    public void updateSetmeal(Long id, Integer status) {
        Setmeal setmeal = new Setmeal();
        setmeal.setId(id);
        setmeal.setStatus(status);
        this.updateById(setmeal);
    }
}
